package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.BaseException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;

@Aspect
@Component
public class AOP  {
    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {

        // 获取签名对象
        //Signature signature = (MethodSignature)joinPoint.getSignature();
        //强转为方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获得注解对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        //获得注解的value值
        OperationType value = annotation.value();
        Object[] args = joinPoint.getArgs();

        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];
        if (value == OperationType.INSERT) {
            //新增，对4个属性赋值
            try {
                Method declaredMethod1 = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                declaredMethod1.invoke(arg, LocalDateTime.now());
                Method declaredMethod2 = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                declaredMethod2.invoke(arg, LocalDateTime.now());
                Method declaredMethod3 = arg.getClass().getDeclaredMethod("setCreateUser", Long.class);
                declaredMethod3.invoke(arg, BaseContext.getCurrentId());
                Method declaredMethod4 = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                declaredMethod4.invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                throw new BaseException("添加失败");
            }

        }
        try {
            Method declaredMethod1 = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            declaredMethod1.invoke(arg, LocalDateTime.now());
            Method declaredMethod4 = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            declaredMethod4.invoke(arg, BaseContext.getCurrentId());
        } catch (Exception e) {
            throw new BaseException("修改失败");
        }


    }
}
